package com.example.xmpic.ui.activity.setting;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.aliyun.iot.aep.component.router.Router;
import com.example.common.base.BaseBindActivity;
import com.example.xmpic.R;
import com.example.xmpic.databinding.ActivityPicSettingCommonBinding;
import com.example.xmpic.support.FunError;
import com.example.xmpic.support.FunSupport;
import com.example.xmpic.support.OnFunDeviceOptListener;
import com.example.xmpic.support.config.CameraParam;
import com.example.xmpic.support.config.FbExtraStateQuery;
import com.example.xmpic.support.models.FunDevice;
import com.example.xmpic.support.utils.DeviceConfigType;
import com.example.xmpic.ui.data.CameraBean;
import com.example.xmpic.ui.utils.CameraDaoUtil;
import com.lib.sdk.struct.H264_DVR_FILE_DATA;

import java.util.Arrays;
import java.util.List;

/**
 * @author skygge
 * @Date on 2020-02-19.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：基本设置
 */
public class CameraSetCommonActivity extends BaseBindActivity<ActivityPicSettingCommonBinding> implements View.OnClickListener,OnFunDeviceOptListener {
    private int id;
    private String deviceId;
    private FunDevice mFunDevice;

    private static final String RENAME_PATH = "https://com.siterwell.familywellplus/page/rename";
    private static final String ROOM_PATH = "https://com.siterwell.familywellplus/page/room";

    /**
     * 本界面需要获取到的设备配置信息（监控类）
     */
    private final String[] DEV_CONFIGS_FOR_CAMERA = { CameraParam.CONFIG_NAME };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pic_setting_common;
    }

    @Override
    protected void initialize() {
        super.initialize();
        id = getIntent().getIntExtra("FUN_DEVICE_ID", 0);
        deviceId = getIntent().getStringExtra("FUN_DEVICE_SN");
    }

    @Override
    public void initView(){
        mFunDevice = FunSupport.getInstance().findDeviceById(id);
        if ( null == mFunDevice ) {
            finish();
            return;
        }
        // 注册设备操作监听
        FunSupport.getInstance().registerOnFunDeviceOptListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        // 获取报警配置信息
        tryGetCameraConfig();
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.updateName.setOnClickListener(this);
        mDBind.modifyRoom.setOnClickListener(this);
        mDBind.btnSwitchCameraFlip.setOnClickListener(this);
        mDBind.btnSwitchCameraMirror.setOnClickListener(this);
        mDBind.ivCommonSettingBack.setOnClickListener(this);
        mDBind.btnOpenStatusLight.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        CameraBean mCameraBean = CameraDaoUtil.getInstance().findCameraByCameraId(deviceId);
        mDBind.updateName.setDetailText(mCameraBean.getDeviceName());
        if (mCameraBean.getRoomName() == null){
            mDBind.modifyRoom.setDetailText(getString(R.string.default_room));
        }else {
            mDBind.modifyRoom.setDetailText(mCameraBean.getRoomName());
        }
    }

    private void tryGetCameraConfig() {
        if (null != mFunDevice) {
            showProgressDialog();
            for (String configName : DEV_CONFIGS_FOR_CAMERA) {
                // 删除老的配置信息
                mFunDevice.invalidConfig(configName);
                //根据是否需要传通道号 重新搜索新的配置信息
                if (contains(DeviceConfigType.DeviceConfigCommon, configName)) {
                    FunSupport.getInstance().requestDeviceConfig(mFunDevice, configName);
                }else if (contains(DeviceConfigType.DeviceConfigByChannel, configName)) {
                    FunSupport.getInstance().requestDeviceConfig(mFunDevice, configName, mFunDevice.CurrChannel);
                }
            }
            FunSupport.getInstance().requestDeviceConfig(mFunDevice, FbExtraStateQuery.CONFIG_NAME);
        }
    }

    public static boolean contains(String[] stringArray, String source) {
        // 转换为list
        List<String> tempList = Arrays.asList(stringArray);

        // 利用list的包含方法,进行判断
        return tempList.contains(source);
    }

    /**
     * 判断是否所有需要的配置都获取到了
     */
    private boolean isAllConfigGetter() {
        for (String configName : DEV_CONFIGS_FOR_CAMERA) {
            if (null == mFunDevice.getConfig(configName)) {
                return false;
            }
        }
        return true;
    }

    private boolean isCurrentUsefulConfig(String configName) {
        for (String s : DEV_CONFIGS_FOR_CAMERA) {
            if (s.equals(configName)) {
                return true;
            }
        }
        return false;
    }

    private void refreshCameraConfig() {
        CameraParam cameraParam = (CameraParam) mFunDevice.getConfig(CameraParam.CONFIG_NAME);
        FbExtraStateQuery fbExtraStateQuery = (FbExtraStateQuery) mFunDevice.getConfig(FbExtraStateQuery.CONFIG_NAME);
        if (null != cameraParam) {
            // 图像上下翻转
            mDBind.btnSwitchCameraFlip.setSelected(cameraParam.getPictureFlip());
            // 图像左右翻转
            mDBind.btnSwitchCameraMirror.setSelected(cameraParam.getPictureMirror());
        }
        if(null!=fbExtraStateQuery){
            mDBind.btnOpenStatusLight.setSelected(fbExtraStateQuery.getIsStateOn() == 1);
        }
    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.iv_common_setting_back) {
            finish();
        } else if (viewId == R.id.update_name) {
            String nickName = mDBind.updateName.getDetailText();
            Bundle bundle = new Bundle();
            bundle.putInt("deviceId", -1);
            bundle.putString("deviceName", deviceId);
            bundle.putString("nickName", nickName);
            Router.getInstance().toUrl(mContext, RENAME_PATH, bundle);
        } else if (viewId == R.id.modify_room) {
            Bundle bundle = new Bundle();
            bundle.putInt("deviceId", -1);
            bundle.putString("deviceName", deviceId);
            bundle.putBoolean("modify_room", true);
            Router.getInstance().toUrl(mContext, ROOM_PATH, bundle);
        } else if (viewId == R.id.btnSwitchCameraFlip) {
            CameraParam cameraParam = (CameraParam) mFunDevice.getConfig(CameraParam.CONFIG_NAME);
            if (null != cameraParam) {
                showProgressDialog();
                // 图像上下翻转
                cameraParam.setPictureFlip(!mDBind.btnSwitchCameraFlip.isSelected());
                FunSupport.getInstance().requestDeviceSetConfig(mFunDevice, cameraParam);
            }
        } else if (viewId == R.id.btnSwitchCameraMirror) {
            CameraParam cameraParam2 = (CameraParam) mFunDevice.getConfig(CameraParam.CONFIG_NAME);
            if (null != cameraParam2) {
                showProgressDialog();
                // 图像上下翻转
                cameraParam2.setPictureMirror(!mDBind.btnSwitchCameraMirror.isSelected());
                FunSupport.getInstance().requestDeviceSetConfig(mFunDevice, cameraParam2);
            }
        } else if (viewId == R.id.btnOpenStatusLight) {
            FbExtraStateQuery fbExtraStateQuery = (FbExtraStateQuery) mFunDevice.getConfig(FbExtraStateQuery.CONFIG_NAME);
            if (null != fbExtraStateQuery) {
                showProgressDialog();
                // 图像上下翻转
                fbExtraStateQuery.setIsStateOn(!mDBind.btnOpenStatusLight.isSelected());
                FunSupport.getInstance().requestDeviceSetConfig(mFunDevice, fbExtraStateQuery);
            }
        }
    }

    @Override
    public void onDeviceLoginSuccess(FunDevice funDevice) {

    }

    @Override
    public void onDeviceLoginFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceGetConfigSuccess(FunDevice funDevice, String configName, int nSeq) {
        if ( null != mFunDevice && funDevice.getId() == mFunDevice.getId()) {
            if(isCurrentUsefulConfig(configName)){
                if (isAllConfigGetter()) {
                    dismissProgressDialog();
                }
                refreshCameraConfig();
            }
            if (FbExtraStateQuery.CONFIG_NAME.equals(configName)){
                Log.i(TAG, "FbExtraStateCtrlSuccess: " );
                FbExtraStateQuery fb = (FbExtraStateQuery) mFunDevice.getConfig(FbExtraStateQuery.CONFIG_NAME);
                mDBind.btnOpenStatusLight.setSelected(fb.getIsStateOn() == 1);
            }
        }
    }

    @Override
    public void onDeviceGetConfigFailed(FunDevice funDevice, Integer errCode) {
        dismissProgressDialog();
        showToast(FunError.getErrorStr(errCode));
    }

    @Override
    public void onDeviceSetConfigSuccess(FunDevice funDevice, String configName) {
        if (null != mFunDevice && funDevice.getId() == mFunDevice.getId()) {
            dismissProgressDialog();
            refreshCameraConfig();
        }
    }

    @Override
    public void onDeviceSetConfigFailed(FunDevice funDevice, String configName, Integer errCode) {
        dismissProgressDialog();
        Toast.makeText(this, FunError.getErrorStr(errCode),Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDeviceChangeInfoSuccess(FunDevice funDevice) {

    }

    @Override
    public void onDeviceChangeInfoFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceOptionSuccess(FunDevice funDevice, String option) {

    }

    @Override
    public void onDeviceOptionFailed(FunDevice funDevice, String option, Integer errCode) {

    }

    @Override
    public void onDeviceFileListChanged(FunDevice funDevice) {

    }

    @Override
    public void onDeviceFileListChanged(FunDevice funDevice, H264_DVR_FILE_DATA[] datas) {

    }

    @Override
    public void onDeviceFileListGetFailed(FunDevice funDevice) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FunSupport.getInstance().removeOnFunDeviceOptListener(this);
    }
}
